import axios from 'axios';
import UserService from './UserService.js';
import { ElMessage } from 'element-plus';
import router from '../router';

// 创建axios实例
const api = axios.create({
    timeout: 10000,
    headers: {
        'Content-Type': 'application/json'
    },
    validateStatus: status => status >= 200 && status < 300
});

// 请求拦截器，自动加token
api.interceptors.request.use(config => {
    const token = localStorage.getItem('token') || (UserService.getCurrentUser && UserService.getCurrentUser().token) || '';
    if (token) {
        config.headers.token = token;
    }
    return config;
});

// 响应拦截器
api.interceptors.response.use(
    (response) => {

        return response
    },
    (error) => {
        //如果响应的状态码为401, 则路由到登录页面
        console.log('响应错误:', error);
        if (error.response.status === 401) {
            ElMessage.error('登录失效, 请重新登录')
            router.push('/login')
        } else {
            ElMessage.success('接口访问异常')
        }
        return Promise.reject(error)
    }
);



class TenantService {
    // 查询租户列表
    async getTenantList(params = {}) {
        try {
            const response = await api.get('/api/tenant/list', { params });
            return response.data;
        } catch (error) {
            console.error('获取租户列表失败:', error);
            throw error;
        }
    }

    // 新增租户
    async addTenant(file, tenant) {
        const formData = new FormData();
        formData.append('file', file);

        Object.keys(tenant).forEach(key => {
            formData.append(key, tenant[key]);
        });

        const response = await api.post('/api/tenant/add', formData, {
            transformRequest: [data => data], // 禁止 JSON 转换
        });

        return response.data;
    }

    // 更新租户
    async updateTenant(tenantId, data, file) {
        const formData = new FormData();

        // 1. 添加文件
        if (file) {
            formData.append('file', file);
        }

        // 2. 将 JSON 数据转为字符串并添加到 FormData
        formData.append('data', JSON.stringify(data));
        try {
            const response = await api.put(`/api/tenant/${tenantId}`, formData, {
                headers: {
                    'Content-Type': 'multipart/form-data', // 让浏览器自动设置正确的 boundary
                },
            });
            return response.data;
        } catch (error) {
            console.error('更新租户失败:', error);
            throw error;
        }
    }

    // 删除租户
    async deleteTenant(tenantId) {
        try {
            const response = await api.delete(`/api/tenant/${tenantId}`);
            return response.data;
        } catch (error) {
            console.error('删除租户失败:', error);
            throw error;
        }
    }

    // 获取租户详情
    async getTenantDetail(tenantId) {
        try {
            const response = await api.get(`/api/tenant/${tenantId}`);
            return response.data;
        } catch (error) {
            console.error('获取租户详情失败:', error);
            throw error;
        }
    }

    // 获取图形验证码
    async getCaptcha() {
        try {
            const response = await api.get('/api/tenant/captcha');
            return response.data;
        } catch (error) {
            console.error('获取验证码失败:', error);
            throw error;
        }
    }

    // 上传租户图标
    async uploadTenantIcon(file) {
        try {
            const formData = new FormData();
            formData.append('file', file);

            const response = await api.post('/api/tenant/uploadIcon', formData, {
                headers: { 'Content-Type': 'multipart/form-data' }
            });
            return response.data;
        } catch (error) {
            console.error('上传租户图标失败:', error);
            throw error;
        }
    }

    // 租户注册
    async register(file, tenant) {
        try {
            const formData = new FormData();
            formData.append('file', file);

            Object.keys(tenant).forEach(key => {
                formData.append(key, tenant[key]);
            });

            const response = await api.post('/api/tenant/register', formData, {
                transformRequest: [data => data], // 禁止 JSON 转换
            });
            console.log('response:asdas', response);
            return response.data;
        } catch (error) {
            console.error('租户注册失败:', error);
            throw error;
        }
    }

    // 删除租户图标
    async deleteTenantIcon(url) {
        try {
            const response = await api.post('/api/tenant/deleteIcon', null, {
                params: { url } // 作为查询参数
            });
            console.log('response:', response);
            return response.data;
        } catch (error) {
            console.error('删除租户图标失败:', error);
            throw error;
        }
    }
}

export default new TenantService(); 